package com.train.redis.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class SerializableUtils {

    public static <T> T parseObject(Object value, Class<T> type) {
        ObjectMapper mapper = new ObjectMapper();
        deserializerDateTime(mapper);
        try {
            String jsonStr = mapper.writeValueAsString(value);
            return mapper.readValue(jsonStr, type);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private static void deserializerDateTime(ObjectMapper mapper) {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter localDateTimeFormatter = getDateTimeFormatter("yyyy-MM-dd HH:mm:ss", "Asia/Shanghai");
        DateTimeFormatter localDateFormatter = getDateTimeFormatter("yyyy-MM-dd", "Asia/Shanghai");
        DateTimeFormatter localTimeFormatter = getDateTimeFormatter("HH:mm:ss", "Asia/Shanghai");
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(localDateFormatter));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(localDateTimeFormatter));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(localTimeFormatter));
        mapper.registerModule(javaTimeModule);
    }

    public static DateTimeFormatter getDateTimeFormatter(String format, String zone) {
        return DateTimeFormatter.ofPattern(format).withZone(ZoneId.of(zone));
    }
}
